package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.SellerMapper;
import com.itheima.travel.pojo.Seller;
import com.itheima.travel.pojo.SellerExample;
import com.itheima.travel.req.SellerVo;
import com.itheima.travel.service.SellerService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class SellerServiceImpl implements SellerService {

    @Autowired
    private SellerMapper sellerMapper;

    @Autowired
    private HttpSession session;

    @Override
    public Boolean registerSeller(SellerVo sellerVo) {
        Seller seller = BeanConv.toBean(sellerVo, Seller.class);
        seller.setPassword(MD5Coder.md5Encode(seller.getPassword()));
        int i = sellerMapper.insert(seller);
        return i>0;
    }

    @Override
    public SellerVo loginSeller(SellerVo sellerVo) {
        SellerExample example = new SellerExample();
        example.createCriteria()
                .andUsernameEqualTo(sellerVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(sellerVo.getPassword()));
        List<Seller> list = sellerMapper.selectByExample(example);

        SellerVo resultSellerVo = null;
        if(list.size() == 1) {
            Seller seller = list.get(0);
            resultSellerVo = BeanConv.toBean(seller, SellerVo.class);
            session.setAttribute(session.getId(), resultSellerVo);
        }
        return resultSellerVo;
    }

    @Override
    public void loginOutSeller() {
        session.removeAttribute(session.getId());
    }

    @Override
    public Boolean isLogin() {
        Object sellerVo = session.getAttribute(session.getId());
        return !EmptyUtil.isNullOrEmpty(sellerVo);
    }

    @Override
    public SellerVo findSellerVoById(SellerVo sellerVo) {
        Seller seller = sellerMapper.selectByPrimaryKey(sellerVo.getId());
        SellerVo resultSellerVo = BeanConv.toBean(seller, SellerVo.class);
        return resultSellerVo;
    }
}
